package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.controller.dto.UpdateDeliveryAddressDto;
import cn.edu.tju.elm.model.DeliveryAddress;
import cn.edu.tju.elm.service.DeliveryAddressService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/addresses")
@Tag(name = "管理配送地址", description = "对配送地址进行增删改查")
public class AddressController {

    @Autowired
    private DeliveryAddressService deliveryAddressService;

    @Autowired
    private UserService userService;

    @PutMapping("/{id}")
    @Operation(summary = "修改配送地址", description = "根据ID修改配送地址信息")
    public HttpResult<DeliveryAddress> updateAddress(
            @PathVariable Long id,
            @Valid @RequestBody UpdateDeliveryAddressDto updateDto) {

        // 获取当前登录用户
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
        }

        // 根据ID和用户ID查询地址
        Optional<DeliveryAddress> addressOptional = deliveryAddressService.findByIdAndCustomerId(id, currentUser.getId());
        if (!addressOptional.isPresent()) {
            return HttpResult.failure(ResultCodeEnum.ADDRESS_NOT_FOUND);
        }

        // 更新地址信息
        DeliveryAddress address = addressOptional.get();
        address.setContactName(updateDto.getContactName());
        address.setContactSex(updateDto.getContactSex());
        address.setContactTel(updateDto.getContactTel());
        address.setAddress(updateDto.getAddress());
        address.setUpdateTime(LocalDateTime.now());

        // 保存更新
        DeliveryAddress updatedAddress = deliveryAddressService.save(address);
        return HttpResult.success(updatedAddress);
    }

    @GetMapping("")
    @Operation(summary = "获取用户配送地址列表", description = "获取当前用户的配送地址列表")
    public HttpResult<List<DeliveryAddress>> getUserAddresses() {
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
        }

        List<DeliveryAddress> addresses = deliveryAddressService.findByCustomerId(currentUser.getId());
        return HttpResult.success(addresses);
    }

    @PostMapping("")
    @Operation(summary = "新增配送地址", description = "为当前用户新增配送地址")
    public HttpResult<DeliveryAddress> addAddress(@Valid @RequestBody UpdateDeliveryAddressDto createDto) {
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
        }

        // 创建新地址
        DeliveryAddress address = new DeliveryAddress();
        address.setContactName(createDto.getContactName());
        address.setContactSex(createDto.getContactSex());
        address.setContactTel(createDto.getContactTel());
        address.setAddress(createDto.getAddress());
        address.setCustomer(currentUser);
        address.setCreateTime(LocalDateTime.now());
        address.setUpdateTime(LocalDateTime.now());

        DeliveryAddress savedAddress = deliveryAddressService.save(address);
        return HttpResult.success(savedAddress);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除配送地址", description = "根据ID删除配送地址")
    public HttpResult<String> deleteAddress(@PathVariable Long id) {
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
        }

        // 检查地址是否存在且属于当前用户
        if (!deliveryAddressService.findByIdAndCustomerId(id, currentUser.getId()).isPresent()) {
            return HttpResult.failure(ResultCodeEnum.ADDRESS_NOT_EXISTS);
        }

        deliveryAddressService.deleteById(id);
        return HttpResult.success("删除成功");
    }
}